<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/Welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card class="box-card">
      <!-- 提示 -->
      <el-alert
        title="注意：只允许为第三级分类设置相关参数！"
        type="warning"
        left
        show-icon
      >
      </el-alert>
      <!-- 级联选择器 props 指定配置选项
        options 指定数据源
        v-model 绑定的是数组 第一个值为一级的id 第二个值为二级的id
        -->
      <el-form>
        <el-form-item label="分类分类">
          <el-cascader
            clearable
            v-model="opcitions"
            :options="parentList"
            :props="catCascProps"
            @change="handleChange"
          ></el-cascader>
        </el-form-item>
      </el-form>
      <!-- tabs栏 -->
      <el-tabs type="border-card" v-model="tabs" @tab-click="tabClick">
        <el-tab-pane label="动态参数" name="many">
          <!-- 添加动态参数的按钮 -->
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtn"
            @click="addParams = true"
            >添加动态参数</el-button
          >
          <!-- table栏的数据 -->
          <el-table :data="tableData" stripe style="width: 100%" border>
            <!-- 展开栏 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 渲染的数据 -->
                <el-tag
                  closable
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="item.id"
                  @close="delRightId(scope.row, i)"
                >
                  {{ item }}
                </el-tag>
                <!-- 添加的内容的input框-->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <!-- 添加的按钮 -->
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column prop="date" type="index" label="#" width="80">
            </el-table-column>
            <el-table-column prop="attr_name" label="参数名称" width="480">
            </el-table-column>
            <el-table-column prop="address" label="操作">
              <template slot-scope="scope">
                <el-button
                  icon="el-icon-edit"
                  type="primary"
                  size="mini"
                  @click="edit(scope.row)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="delParams(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <!-- 添加静态属性的按钮 -->
          <el-button
            type="primary"
            size="mini"
            :disabled="opcitions.length !== 3"
            @click="addParams = true"
            >添加静态属性</el-button
          >
          <!-- table栏的数据 -->
          <el-table :data="tableData" stripe style="width: 100%" border>
            <!-- 展开栏 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 显示的标签 -->
                <el-tag
                  closable
                  v-for="item in scope.row.attr_vals"
                  :key="item.id"
                  @close="delRightId(scope.row, item.id)"
                >
                  {{ item }}
                </el-tag>
                <!-- 添加的内容的input框-->
                <!-- 添加的内容的input框-->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <!-- 添加的按钮 -->
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column prop="date" type="index" label="#" width="80">
            </el-table-column>
            <el-table-column prop="attr_name" label="参数名称" width="480">
            </el-table-column>
            <el-table-column prop="address" label="操作">
              <template slot-scope="scope">
                <el-button
                  icon="el-icon-edit"
                  type="primary"
                  size="mini"
                  @click="edit(scope.row)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="delParams(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加的弹框 -->
    <el-dialog
      title="添加"
      :visible.sync="addParams"
      @close="close"
      width="30%"
    >
      <!--  :before-close="handleClose" -->
      <!-- 表单 model列表的数据 rules验证规则 ref绑定的ref-->
      <!--v-model="" -->
      <el-form v-model="addRole">
        <el-form-item :label="tabs === 'many' ? '动态参数' : '静态属性'">
          <el-input v-model="addRole.roleName"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addParams = false">取 消</el-button>
        <el-button type="primary" @click="paramsClick()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改的弹框 -->
    <el-dialog
      title="提示"
      :visible.sync="editParams"
      @close="close"
      width="30%"
    >
      <el-form v-model="addRole">
        <el-form-item :label="tabs === 'many' ? '修改参数' : '修改属性'">
          <el-input v-model="addRole.roleName"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editParams = false">取 消</el-button>
        <el-button type="primary" @click="editClick()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import http from '../util/http'
export default {
  data () {
    return {
      // 选择数据的id
      opcitions: [],
      // 级联表的配置
      catCascProps: {
        value: 'cat_id', // 选中值的id
        label: 'cat_name', // 看到的值
        childred: 'childred', // 父子嵌套的属性
        expandTrigger: 'hover'
        // checkStrictly: true,
      },
      // 级联表数据
      parentList: [],
      //  tab选项卡默认选择那个栏
      tabs: 'many',
      //   table的数据
      tableData: [],
      //   添加动态参数的弹出框
      addParams: false,

      // 添加的表单数据
      addRole: {
        roleName: ''
      },
      // 分类的id
      id: null,
      // 编辑的弹框
      editParams: false,
      // 属性的id
      attr_id: null,
      // 添加展开行内容
      inputValue: '',
      // 按钮和输入框切换的布尔值
      inputVisible: false
    }
  },
  mounted () {
    this.getParams()
    // console.log(this.tabs);
  },
  methods: {
    //   获取数据
    getParams () {
      http('categories').then((res) => {
        console.log(res.data.data)
        this.parentList = res.data.data
      })
    },
    //   当级联选择完成时候
    handleChange () {
      console.log(this.opcitions)
      if (this.opcitions.length !== 3) {
        this.opcitions = []
        this.tableData = []
      } else {
        const id = this.opcitions[this.opcitions.length - 1]
        this.id = id
        http({
          url: `categories/${id}/attributes`,
          method: 'get',
          params: { sel: this.tabs }
        }).then((res) => {
          console.log(res.data)
          // 把字符串的数据变成数组的形式出现
          res.data.data.forEach((item) => {
            item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : [];
            // 给他添加一个布尔值的属性
            (item.inputVisible = false)(
              // 添加一直值
              (item.inputValue = '')
            )
          })
          this.tableData = res.data.data
        })
      }

      //   console.log(id);
    },
    // tab切换栏的点击事件
    tabClick () {
      console.log(this.tabs)
      this.handleChange()
    },

    // 添加的确定框
    paramsClick () {
      //   console.log(this.id);
      http({
        method: 'post',
        url: `categories/${this.id}/attributes`,
        data: {
          attr_sel: this.tabs,
          attr_name: this.addRole.roleName
        }
      }).then((res) => {
        console.log()
        if (res.data.meta.status === 201) {
          this.$message.success('创建成功')
          this.handleChange()
          this.addRole.roleName = ''
        } else {
          this.$message.error('创建失败')
        }
      })

      this.addParams = false
    },
    // 点击编辑
    edit (row) {
      // console.log(22);
      // console.log(row);
      this.attr_id = row.attr_id
      this.editParams = true
      this.addRole.roleName = row.attr_name
    },
    // 点击删除
    async delParams (row) {
      console.log(row.attr_id)

      const res = await this.$confirm(
        '此操作将永久删除此分类, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch((error) => error)

      if (res === 'confirm') {
        // console.log(22);
        http({
          url: `categories/${this.id}/attributes/${row.attr_id}`,
          method: 'delete'
        }).then((res) => {
          console.log(res.data.meta.status)
          if (res.data.meta.status === 200) {
            this.$message.success('删除成功')
            this.handleChange()
          } else {
            this.$message.success('删除失败')
          }
        })
      } else {
        // console.log(11);
        this.$message.error('取消删除')
      }
      // http({
      //   url: `categories/${this.id}/attributes/${row.attr_id}`,
      //   method: "delete",
      // }).then((res) => {
      //   console.log(res.data.meta.status);
      //   if (res.data.meta.status === 200) {
      //     this.$message.success("删除成功");
      //   }
      // });
    },
    // 确定修改
    editClick () {
      // this.handleChange()
      http({
        method: 'put',
        url: `categories/${this.id}/attributes/${this.attr_id}`,
        data: {
          attr_name: this.addRole.roleName,
          attr_sel: this.tabs
        }
      }).then((res) => {
        // console.log(res.data.meta.status);
        if (res.data.meta.status === 200) {
          this.$message.success('修改成功')
          this.handleChange()
          this.addRole.roleName = ''
        } else {
          this.$message.error('修改失败')
        }
      })
      this.editParams = false
    },
    // 跳出弹出框的时候
    close () {
      this.addRole.roleName = ''
    },
    // 添加展开行内容的按钮
    handleInputConfirm (row) {
      // 判断有没有输入内容 trim()把空格清除
      if (row.inputValue.trim().length === 0) {
        // 没有输入内容
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      // 如果没有return证明输入了内容
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      row.inputVisible = false
      // 请求数据
      this.saveAttr(row, '添加')
    },
    // 点击按钮展开文本框
    showInput (row) {
      row.inputVisible = true
      // $nextTick当页面重新渲染之后，在执行回调函数里的代码
      this.$nextTick(() => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 删除和请求参数展开行的数据
    saveAttr (row, s) {
      http({
        method: 'put',
        url: `categories/${this.id}/attributes/${row.attr_id}`,
        data: {
          attr_name: row.attr_name,
          attr_sel: this.tabs,
          attr_vals: row.attr_vals.join(' ')
        }
      }).then((res) => {
        if (res.data.meta.status === 200) {
          this.$message.success(`${s}成功`)
        } else {
          this.$message.error(`${s}失败`)
        }
      })
    },
    // 删除展开行的数据
    delRightId (row, i) {
      row.attr_vals.splice(i, 1)
      // 删除的数据保存到数据库
      this.saveAttr(row, '删除')
      // console.log(row.attr_id);
      // console.log(id);
    }
  },
  computed: {
    isBtn () {
      if (this.opcitions.length !== 3) {
        return true
      } else {
        return false
      }
    }
  }
}
</script>
